package com.doge.walknovel.business.reader.menus

import android.content.Context
import android.graphics.Typeface
import android.util.AttributeSet
import android.view.LayoutInflater
import androidx.constraintlayout.widget.ConstraintLayout
import com.doge.wnpro.R
import com.doge.walknovel.analysis.analysisEvent
import com.doge.walknovel.analysis.typeface_changed
import com.doge.wnpro.databinding.LayoutReaderTypefaceBinding
import com.doge.walknovel.utils.setOnClickCallback

class ReaderTypefaceView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null
) : ConstraintLayout(context, attrs) {
    private val binding =
        LayoutReaderTypefaceBinding.inflate(LayoutInflater.from(context), this)

    private var clickedTypeface: Typeface? = null

    init {
        binding.fontFutura.typeface = ReaderHelper.typeFaceFutura
        binding.fontMonaco.typeface = ReaderHelper.typeFaceMonaco
        binding.fontSystem.typeface = Typeface.DEFAULT
        binding.viewFutura.setOnClickCallback {
            ReaderHelper.changeTypeFace(ReaderHelper.typeFaceFutura)
            clickedTypeface = ReaderHelper.typeFaceFutura
            update()
        }
        binding.viewMonaco.setOnClickCallback {
            ReaderHelper.changeTypeFace(ReaderHelper.typeFaceMonaco)
            clickedTypeface = ReaderHelper.typeFaceMonaco
            update()
        }
        binding.viewSystem.setOnClickCallback {
            ReaderHelper.changeTypeFace(Typeface.DEFAULT)
            clickedTypeface = Typeface.DEFAULT
            update()
        }
        update()
    }

    private fun update() {
        val selected = ReaderHelper.typeface
        binding.fontFutura.setBackgroundResource(
            if (selected == ReaderHelper.typeFaceFutura) R.drawable.shape_typeface_selected else R.drawable.shape_000000_20
        )
        binding.fontMonaco.setBackgroundResource(
            if (selected == ReaderHelper.typeFaceMonaco) R.drawable.shape_typeface_selected else R.drawable.shape_000000_20
        )
        binding.fontSystem.setBackgroundResource(
            if (selected == Typeface.DEFAULT) R.drawable.shape_typeface_selected else R.drawable.shape_000000_20
        )
    }

    fun analysisUsingTypeface() {
        val usingTypeface = clickedTypeface ?: return
        analysisEvent(
            "${typeface_changed}_${when (usingTypeface) {
                ReaderHelper.typeFaceFutura -> "FuturaHandwritten"
                ReaderHelper.typeFaceMonaco -> "Monaco"
                else -> "System"
            }}"
        )
        clickedTypeface = null
    }
}

